import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import cookie from 'js-cookie'
import store from '../store'
import platform from '../util/platform'

Vue.use(VueRouter)

const scrollBehavior = (to, from, savedPosition) => {
  if (savedPosition) {
    // 仅点击浏览器前进后退按钮时.
    return savedPosition
  }
  const position = {}
  if (to.hash) {
    position.selector = to.hash
  }
  position.x = 0
  position.y = 0
  return position
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.NODE_ENV === 'production' ? '/m/' : '',
  scrollBehavior,
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if (store.state.token && cookie.get('Authorization')) {
      next()
    } else {
      if (platform.app) {
        setTimeout(() => {
          window.location.replace('jiuji://m.9ji.com/login')
        }, 200)
        if (!platform.android) { // 安卓APP兼容
          next()
        }
      } else {
        let baseUrl = process.env.NODE_ENV === 'production' ? 'https://' + window.location.host + '/m' : 'http://127.0.0.1:8080'
        let loginUrl = 'https://m.9ji.com/acount/login.aspx'
        window.location.replace(loginUrl + '?url=' + encodeURIComponent(baseUrl + to.fullPath))
      }
    }
  } else {
    next()
  }
  if (to.matched.some(r => r.meta.title)) {
    document.title = to.meta.title
    next()
  }
})

export default router
